package com.mall.product.exception;

import com.mall.common.exception.BaseCodeEnum;
import com.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 * 捕获异常并返回相关状态码及信息
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.mall.product.controller")
@RestControllerAdvice(basePackages = "com.mall.product.controller")
public class MallExceptionControllerAdvice {
    /**
     * 统一处理数据校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据出现异常{},异常类型{}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach((fileError) -> {
            map.put(fileError.getField(), fileError.getDefaultMessage());
        });
        return R.error(BaseCodeEnum.VALID_EXCEPTION.getCode(), BaseCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    /**
     * 处理其他所有异常
     *
     * @param t
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable t) {
        log.error("数据出现异常{},异常类型{}", t.getMessage(), t.getClass());
        return R.error(BaseCodeEnum.UNKNOWN_EXCEPTION.getCode(), BaseCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
